#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 备案信息
import requests
import time
import hashlib
import json
import base64
import aircv as ac
import tldextract
import cv2
import numpy as np

from fake_useragent import UserAgent
from requests.packages import urllib3
from requests.adapters import HTTPAdapter

class Beian(object):      #定义一个类
    def __init__(self,domain):     #初始化
        self.domain = domain    # 接受域名信息
        self.result = []    # 定义一个列表，接受返回结果
    def run(self):
        print("[*]正在通过ICP查询网站备案信息[*]")
        try:
            urllib3.disable_warnings()
            s = requests.Session()
            s.keep_alive = False
            s.mount('http://', HTTPAdapter(max_retries=3))
            s.mount('https://', HTTPAdapter(max_retries=3))
            #获取authkey
            token_url = 'https://hlwicpfwc.miit.gov.cn/icpproject_query/api/auth'
            timestamp = int(time.time()*1000)
            authkey = hashlib.md5(f'testtest{timestamp}'.encode('utf-8')).hexdigest()
            data_token = {
                    "authKey": authkey,
                    "timeStamp": timestamp
            }

            headers = {
                    'Host': 'hlwicpfwc.miit.gov.cn',
                    'Origin': 'https://beian.miit.gov.cn',
                    'Referer': 'https://beian.miit.gov.cn/',
                    'User-Agent': UserAgent(verify_ssl=False).random,
            }
            token = ''
            token_response = s.post(token_url, headers=headers, data=data_token, timeout=10, verify=False).json()
            token = token_response.get('params').get('bussiness')
            #print(token)
            #获取验证码图片
            get_big_img = 'https://hlwicpfwc.miit.gov.cn/icpproject_query/api/image/getCheckImage'
            headers_img = {
                    'Host': 'hlwicpfwc.miit.gov.cn',
                    'Origin': 'https://beian.miit.gov.cn',
                    'Referer': 'https://beian.miit.gov.cn/',
                    'User-Agent': UserAgent(verify_ssl=False).random,
                    'token': token,
            }
            img_response = s.post(get_big_img, headers=headers_img, timeout=10, verify=False).json()
            big_img = img_response.get('params').get('bigImage')
            small_image = img_response.get('params').get('smallImage')
            uuid = img_response.get('params').get('uuid')
            big_data = base64.b64decode(big_img)
            img_array = np.frombuffer(big_data, np.uint8)
            im_bg_img = cv2.imdecode(img_array, cv2.COLOR_RGB2BGR)
            small_data = base64.b64decode(small_image)
            img_array = np.frombuffer(small_data, np.uint8)
            im_small_img = cv2.imdecode(img_array, cv2.COLOR_RGB2BGR)
            pos = ac.find_template(im_bg_img, im_small_img, threshold=0.001)
            rec = pos['rectangle']
            dis = rec[0][0]
            if not dis:
                dis = 0
            #获取验证码匹配结果
            check_url = 'https://hlwicpfwc.miit.gov.cn/icpproject_query/api/image/checkImage'
            headers_check = {
                    'Host': 'hlwicpfwc.miit.gov.cn',
                    'Origin': 'https://beian.miit.gov.cn',
                    'Referer': 'https://beian.miit.gov.cn/',
                    'User-Agent': UserAgent(verify_ssl=False).random,
                    'token': token,
                    'Content-Type': 'application/json',
                }
            data_check = {
                    'key': uuid,
                    'value': dis,
                }
            check_response = requests.post(check_url, headers=headers_check, data=json.dumps(data_check), timeout=10, verify=False)
            check_response1 = check_response.json()
            sign = check_response1.get('params')
            #print(sign)
            #获取备案信息
            last_url = 'https://hlwicpfwc.miit.gov.cn/icpproject_query/api/icpAbbreviateInfo/queryByCondition'
            headers_last = {
                    'Host': 'hlwicpfwc.miit.gov.cn',
                    'Origin': 'https://beian.miit.gov.cn',
                    'Referer': 'https://beian.miit.gov.cn/',
                    'User-Agent': UserAgent(verify_ssl=False).random,
                    'token': token,
                    'Content-Type': 'application/json',
                    'sign': sign
                }
            last_data = {
                    "pageNum": "",
                    "pageSize": "",
                    "unitName": self.domain
                }
            last_response = requests.post(last_url, headers=headers_last, data=json.dumps(last_data), timeout=10, verify=False).json()
            last = last_response.get('params').get('list')[0]
            icp = last.get('serviceLicence', '')
            company_name = last.get('unitName', '')
            natureName = last.get('natureName','')
            item = "网站备案号:"+icp+"\n"+"主办单位名称:"+company_name+"\n"+"主办单位性质:"+natureName
            return item
        except Exception as e:
            return None